package com.zzyl.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertDataService;
import com.zzyl.service.AlertRuleService;
import com.zzyl.service.RedisService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.AlertDataVo;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

@Component
public class MyTask {

    //    @Scheduled(fixedRate = 2000) //固定速率，每隔2秒执行一次方法
    @Scheduled(cron = "0 1-30 * * * ?")
    public void task() {
        System.out.println(LocalDateTime.now());
    }

    @Autowired
    private AlertRuleService alertRuleService;

    @Autowired
    private AlertDataService alertDataService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private ExecutorService executorService;

    // 每分钟第0秒触发一次
    // 查找超出规则的数据
    @Scheduled(cron = "0 * * * * ?")
    public void alertDataTask() {
        // 查询所有规则
        List<AlertRule> allAlertRules = alertRuleService.selectByFunctionId(null, null, null);
        if (ObjectUtil.isEmpty(allAlertRules)) {
            return;
        }
        // 查询缓存中最新上报的数据,并进行转换
        // 已经获取到了获取单个设备的list数据，并完成校验
        Map<String, List<DeviceDataVo>> deviceDataVoMap = redisService.getAllLatestDeviceData();
        if (ObjectUtil.isEmpty(deviceDataVoMap)) {
            return;
        }
        // 一个设备一个线程
        for (Map.Entry<String, List<DeviceDataVo>> entry : deviceDataVoMap.entrySet()) {

            List<DeviceDataVo> deviceDataVos = entry.getValue();
            // 2. 规则校验（根据规则进行校验）
            List<AlertRule> alertRules = new ArrayList<>();
            // 3. 数据格式标准化（统一格式，便于后续规则校验）
            for (DeviceDataVo deviceDataVo : deviceDataVos) {
                String iotId = deviceDataVo.getIotId();
                String productKey = deviceDataVo.getProductKey();
                // 合并设备的报警规则
                alertRules.addAll(alertDataService.normalize(iotId, productKey, allAlertRules));
                // 判断是否为空
                if (ObjectUtil.isEmpty(alertRules)) {
                    return;
                }
                // 4. 执行报警处理
                for (DeviceDataVo d : deviceDataVos) {
                    alertDataService.process(d, alertRules);
                }
            }

        }

    }
}
